﻿using Md.Api.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Md.Api.Controllers.Filters;
/// <summary>
/// 实体验证拦截器
/// </summary>
public class MdModelValidateAttribute : IActionFilter
{
    /// <summary>
    /// 响应实体
    /// </summary>
    private ResponseMessageModel? Result { get; set; }
    /// <summary>
    /// 在操作执行之后、操作结果之前调用。
    /// </summary>
    /// <param name="context"></param>
    public void OnActionExecuted(ActionExecutedContext context)
    {
        
    }
    /// <summary>
    /// 在模型绑定完成后、操作执行之前调用。
    /// </summary>
    /// <param name="context"></param>
    public void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            var errorCodeList = context.ModelState.Select(s => s.Value.Errors.First().ErrorMessage).ToList();

            var errorMsgList = new List<string>();

            errorCodeList.ForEach(errorMsgList.Add); // 此处可执行国际化（全球化翻译）

            if (errorMsgList.Count() > 0)
            {
                Result = new ResponseMessageModel();
                Result.Msg = string.Join("|", errorMsgList);
                Result.Code = "500";
                Result.IsSuccess = false;

                context.Result = new OkObjectResult(Result);
            }
        }
    }
}